package com.administrator.scoreManageSys.config.system;

import com.administrator.scoreManageSys.system.ReturnMsg;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.administrator.scoreManageSys.system.ReturnMsg.RUNTIM_EXC;
import static com.administrator.scoreManageSys.system.ReturnMsg.TOKEN_EXC;
import static com.administrator.scoreManageSys.system.SystemConstant.REST_ERROR_ENDPOINT;

/**
 * 自定义错误处理控制器
 *
 * @author lufan
 * @version 1.0
 * @date 2018/1/24
 */
@RestController
public class RestErrorEndpoint implements ErrorController {

    private static final String ERROR_PATH = "/error";
    private static final String ERROR = "javax.servlet.error.exception";
    private static final String LOGIN_EXCEPTION = "登录失效请重新登录";


    @RequestMapping(value = ERROR_PATH)
    public JSONObject handleError(HttpServletRequest request) {
        // 总的返回数据
        JSONObject jsonObject = new JSONObject();
        if (request.getAttribute(ERROR) != null) {
            String errorException = request.getAttribute(ERROR).toString();
            String reg = "[^\u4e00-\u9fa5]";
            errorException = errorException.replaceAll(reg, "");
            if (errorException.equals(LOGIN_EXCEPTION)){
                jsonObject.put("code", 401);
                jsonObject.put("msg",  errorException);
            }else {
                jsonObject.put("code", 201);
                jsonObject.put("msg",  request.getAttribute(ERROR).toString());
            }
        }
        //其它业务数据
        jsonObject.put("data", new JSONObject());
        System.out.println("错误信息" + jsonObject);
        return jsonObject;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

}
